import uniPopupDialog from '@/uni_modules/uni-popup/components/uni-popup-dialog/uni-popup-dialog.vue'
const { isEmojiCharacter } = require('@/utils/util.js');
export const settingMixins = {
	components: {
		uniPopupDialog
	},
	data() {
		return {
			device: {
				token: '',
				deviceNo: '',
				deviceName: '',
				devUserName: '',
			},
			editDeviceName: "",
			deviceName: '',
			focus: false,
			DeviceIP: "",
			door_lock_subscri: uni.getStorageSync('door_lock_subscri') ? true : false,
			timer:null,
			updateStatus: false,
			isLoginSuccess:false,
			isSupportLockSetting:false,
			isSupportUserManager:false,
			userTypeMsk:'',
			enableMultiModule:false,//是否支持锁具升级
			DoorFunction:null,//门锁设置能力集
		};
	},
	onLoad(opt) {
		let enData = decodeURIComponent(opt.device)
		this.device = JSON.parse(enData)
		console.log('设备设置页===',this.device);
		// this.deviceName = this.device.deviceName;
		let deviceList = uni.getStorageSync('deviceList');
		if(deviceList.length>0){
			for (let i = 0; i < deviceList.length; i++) {
				const item = deviceList[i];
				if (item.deviceNo === this.device.deviceNo) {
					this.deviceName = item.deviceName;
					break;
				}
			}
		}else{
			this.deviceName = this.device.deviceName
		}
		this.timer  = setTimeout(()=>{
			// this.$logs({info: '预览到设置页60秒后销毁保活定时器',timer:getApp().globalData.keepTimer})
			console.log('预览到设置页60秒后销毁保活定时器',getApp().globalData.keepTimer,this.timer);
			if(this.timer){
				if(getApp().globalData.keepTimer && !this.updateStatus){
					clearInterval(getApp().globalData.keepTimer);
					getApp().globalData.keepTimer = null
					clearTimeout(this.timer)
					this.timer = null
				}
			}
		},60000)
		this.getTailoredConfig()
	},
	onUnload(){
		this.timer = null
		clearTimeout(this.timer)
		if(this.isLoginSuccess){
			this.deviceLogOut()
		}
	},
	methods: {
		//获取影子服务接口
		getTailoredConfig() {
			let token = this.device.token
			let data = {
				"sn": this.device.deviceNo,
				"configs": []
			};
			getApp().globalData.api.getTailoredConfig(data, token, (result) => {
				console.log('设置页离线配置==',result);
				if(result.dlctrl){
					let flag = []
					if(result.dlctrl.DlSet){
						if(Object.keys(result.dlctrl.DlSet).findIndex(item=>result.dlctrl.DlSet[item] == true)!=-1){
							this.isSupportLockSetting = true
						}
					}
					if(result.dlctrl.DlUser&&Object.keys(result.dlctrl.DlUser).length > 0){
						this.isSupportUserManager = true
						this.userTypeMsk = result.dlctrl.DlUser.TypeMsk
					}
					this.enableMultiModule = result.dlctrl.Upgrade;
					this.DoorFunction =  result.dlctrl.DlSet
				}
			})
		},
		//设备登出
		deviceLogOut() {
			let token = this.device.token
			let data = {
				Name: 'Logout',
			};
			getApp().globalData.api.deviceLogOut(data, token, (result) => {
				console.log(result, '登出-setting')
				this.$logs({info:'从设置页退出登录'})
			});
		},
		getLogin(callback) {
			uni.showLoading({
				mask:true,
			});
			let token = this.device.token;
			let data = {
				encryptType: 'DISABLE',
				LoginType: 'DVRIP-Web',
				UserName: 'admin',
				PassWord: this.device.devPassWord,
				Name: 'generalinfo'
			};
			if (this.device.adminToken) {
				data.LoginToken = this.device.adminToken
				data.encryptType = 'TOKEN'
			}
			getApp().globalData.api.deviceLogin(data, token, (result) => {
				uni.hideLoading();
				if (result.data.code === 2000) {
					// 登录成功 或 已登录
					if (result.data.data.Ret === 100 || result.data.data.Ret === 104) {
						console.log('成功')
						callback()
					} // 出错
					else {
						uni.showToast({
							icon:'none',
							title: getApp().globalData.errCodeMsg.RetCodeMsg[result.data.data.Ret]||result.data.data.RetMsg,
						});
						setTimeout(()=>{
							uni.navigateBack()
						},1000)
					}
				}else{
					uni.showToast({
						icon:'none',
						title: getApp().globalData.errCodeMsg.CodeMsg[result.data.code] || result.data.msg
					});
					setTimeout(()=>{
						uni.navigateBack()
					},1000)
				}
			})
		},
		// 获取设备信息
		getinfo(callback) {
			// uni.showLoading({
			// 	title: '获取设备基础信息...'
			// });
			let token = this.device.token;
			const data = {
				Name: 'SystemInfo'
			};
			let info = {}
			setTimeout(()=>{
				uni.hideLoading()
			},6000)
			getApp().globalData.api.getinfo(data, token, (res) => {
				callback(res)
			});
			return info
		},
		// 获取升级版本
		getDeviceVersion(data, token, callback, decode = false, simple = true) {
			getApp().globalData.api.opdev(data, token, (res) => {
				callback(res)
			}, decode, simple)
		},
		// 低功耗设备唤醒
		wakeup(callback,decode = false, simple = false) {
			let data={
				sn:this.device.deviceNo,
				hostedControl:"1",//是否唤醒主控（空值或0：不唤醒主控；1：唤醒主控）
			}
			getApp().globalData.api.wakeup(data,this.device.token, (result) => {
				callback(result);
			}, decode, simple);
		},
		
		settingFunc(v) {
			let url = `${'./'+v}?device=${encodeURIComponent(JSON.stringify(this.device))}`
			if(v=='powerSaving'){
				url = `${'./'+v}?device=${encodeURIComponent(JSON.stringify(this.device))}&powerSavingMode=${encodeURIComponent(JSON.stringify(this.powerSavingMode))}`
			}
			uni.navigateTo({
				url: url
			});
		},
		// 移动房间
		mobileDevices() {
			uni.navigateTo({
				url: `/jvss/pagesDevice/device/room-select/room-select?device=${encodeURIComponent(JSON.stringify(this.device))}&type=3`
			});
		},
		// 移除设备
		removeDevice() {
			uni.showModal({
				title: '提示',
				content: '确认删除此设备？',
				success: (response) => {
					if (response.confirm) {
						const data = {
							deviceNo: this.device.deviceNo,
							clearNss:false
						};
						getApp().globalData.api.delDevice(data, (result) => {
							uni.showToast({
								title: '成功删除！'
							});
						});
					}
				}
			});
		},
		// 开关
		switchChange(e) {
			console.log('switch', e.detail);
			let isOpen = e.detail.value
			let token = this.device.token
			if (isOpen) {
				this.openMessage({
					callbackUrl: ''
				}, token)
			} else {
				this.closeMessage(token)
			}

		},
		//开通订阅报警消息
		openMessage(data, token) {
			getApp().globalData.api.subscribeMessage(data, token, (result) => {
				uni.showToast({
					title: '开通成功'
				})
				uni.setStorageSync('door_lock_subscri', 'true')
			});
		},
		//取消订阅报警消息
		closeMessage(token) {
			getApp().globalData.api.unsubscribeMessage(token, (result) => {
				uni.showToast({
					title: '取消成功'
				})
				uni.removeStorageSync('door_lock_subscri')
			});
		},
		// 修改设备名称
		submit() {
			if (this.editDeviceName.replace(/\s/g, '') === '') {
				uni.showToast({
					title: '请输入设备名称',
					icon:'none'
				});
				return;
			}
			if(this.editDeviceName.length>32 || this.editDeviceName.length<2){
				uni.showToast({
					title: '设备名称长度2~32位',
					icon:'none'
				});
				return;
			}
			if(isEmojiCharacter(this.editDeviceName)){
				uni.showToast({
					title: '设备名称不能为表情包',
					icon:'none'
				});
				return;
			}
			let data = {
				deviceNo: this.device.deviceNo,
				deviceName: this.editDeviceName
			};
			getApp().globalData.api.updateDevice(data, (result) => {
				uni.showToast({
					title: '修改成功'
				})
				this.deviceName = this.editDeviceName
				this.$refs.inputDialog.close()
				this.focus = false
				let deviceList = uni.getStorageSync('deviceList');
				for (let i = 0; i < deviceList.length; i++) {
					const item = deviceList[i];
					if (item.deviceNo === this.device.deviceNo) {
						item.deviceName = this.deviceName;
						break;
					}
				}
				let jsonData = {
					sn:this.device.deviceNo,
					deviceName:this.editDeviceName
				}
				uni.$emit('editDeviceName',jsonData)
				console.log(deviceList, '修改完重新缓存')
				uni.setStorageSync('deviceList', deviceList);
			});
		},
		// 显示修改设备名称弹框
		openPopup() {
			this.$refs.inputDialog.open()
			this.editDeviceName = this.deviceName
		},
		//关闭弹框
		close() {
			this.$refs.inputDialog.close()
			this.deviceName = this.device.deviceName
		},
	}
};
